define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index  : function () {
        // 初始化表格参数配置
            Table.api.init();
            //绑定事件
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var panel = $($(this).attr("href"));
                if (panel.length > 0) {
                    Controller.table[panel.attr("id")].call(this);
                    $(this).on('click', function (e) {
                        $($(this).attr("href")).find(".btn-refresh").trigger("click");
                    });
                }
                //移除绑定的事件
                $(this).unbind('shown.bs.tab');
            });

            //必须默认触发shown.bs.tab事件
            $('ul.nav-tabs li.active a[data-toggle="tab"]').trigger("shown.bs.tab");

            $(document).on('click', '.show-detail', function (data) {
                var area = ['95%', '95%'];
                var options = {
                    shadeClose : false,
                    shade      : [0.3, '#393D49'],
                    area       : area,
                    callback   : function (value) {
                        //在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
                        console.log(value);
                    },
                    end:function (){
                        $('.btn-refresh').trigger('click');
                    }
                };
                Fast.api.open($.fn.bootstrapTable.defaults.extend.detail_url + "?ids=" + $(this).data('id'), '发货单', options);
            });
            $(document).on('click', '.show-customer', function (data) {
                var area = ['95%','95%'];
                var options = {
                    shadeClose : false,
                    shade      : [0.3, '#393D49'],
                    area       : area,
                    callback   : function (value) {
                        //在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
                        console.log(value);
                    }
                };
                Fast.api.open("qingdongwms/customer/customer/detail?ids=" + $(this).data('id'), '客户详情', options);
            });

        },
        tableinfo:{
            url          : '',
            toolbar: '#toolbar',
            pk           : 'id',
            sortName     : 'id',
            fixedColumns : true,
            fixedNumber  : 2,
            fixedRightNumber  : 1,
            columns      : [
                [
                    {
                        field : 'num', title : '发货单编号', fixedColumns : true, formatter : function (value, row, index) {

                            return "<a href='javascript:void(0);' data-id='" + row.id + "' class='show-detail'>" + value + "</a>";
                        },operate:'like'
                    },
                    {field : 'customer', title : '客户名称', formatter : function (value, row, index) {
                            if(row.customer){
                                return "<a href='javascript:void(0);' data-id='" + row.customer_id + "' class='show-customer'>" + row.customer.name + "</a>";
                            }
                            return '';
                        },operate:false},
                    {field : 'warehouse.name', title : '发货仓库',operate:false},
                    {field : 'money', title : '发货单金额',operate:false},
                    {field : 'export_number', title : '打印次数',operate:false},
                    {field : 'check_status', title : '审核状态',formatter:Table.api.formatter.status, searchList: {0:'待审核', 1: '审核中',2:'审核通过',3:"审核未通过",4:"已撤销",9:"已作废"}},
                    {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                    {field : 'updatetime', title : '更新时间',operate:false},


                ]
            ],
            pagination        : true,
            search            : false,
            commonSearch      : true,
            searchFormVisible : true,
            //显示导出按钮
            showExport: false,
            onLoadSuccess:function(){
                // 这里就是数据渲染结束后的回调函数
                $(".btn-add").data("area",["90%","90%"]);
                $(".btn-edit").data("area",["80%","80%"]);
            }
        },
        table: {
            first: function () {
                // 初始化表格参数配置
                Table.api.init({
                    extend : {
                        add_url    : 'qingdongwms/customer/delivery/add',
                        detail_url : 'qingdongwms/customer/delivery/detail',
                        table      : 'delivery',
                    }
                });

                if(Config.fields !='[]'){
                    if (Config.fields && Object.keys(Config.fields).length > 0) {
                        var fields = JSON.parse(Config.fields);
                        var start = Controller.tableinfo.columns[0].length-3;
                        for (var i = 0; i < fields.length; i++) {
                            if (fields[i].hasOwnProperty('formatter'))
                                fields[i].formatter = eval(fields[i].formatter);
                            if (fields[i].hasOwnProperty('events'))
                                fields[i].events = eval(fields[i].events);
                            if (fields[i].hasOwnProperty('searchList'))
                                fields[i].searchList = JSON.parse(fields[i].searchList);
                            Controller.tableinfo.columns[0].splice(start + i, 0, fields[i]);
                        }
                    }

                }1
                var table = $("#table");
                Controller.tableinfo.url=location.href+'&type=0';
                Controller.tableinfo.toolbar='#toolbar';
                Controller.tableinfo.columns[0][Controller.tableinfo.columns[0].length-1].table=table;
                // 初始化表格
                table.bootstrapTable(Controller.tableinfo);

                // 为表格绑定事件
                Table.api.bindevent(table);
            },
            second: function () {
                // 初始化表格参数配置
                Table.api.init({
                    extend : {
                        add_url    : 'qingdongwms/customer/delivery/add',
                        detail_url : 'qingdongwms/customer/delivery/detail',
                        table      : 'delivery',
                    }
                });
                Controller.tableinfo.url=location.href+'&type=1';
                Controller.tableinfo.toolbar='#toolbar1';
                var table = $("#table1");
                // 初始化表格
                table.bootstrapTable(Controller.tableinfo);

                // 为表格绑定事件
                Table.api.bindevent(table);
            },
            third: function () {
                // 初始化表格参数配置
                Table.api.init({
                    extend : {
                        add_url    : 'qingdongwms/customer/delivery/add',
                        detail_url : 'qingdongwms/customer/delivery/detail',
                        table      : 'delivery',
                    }
                });

                var table = $("#table2");
                Controller.tableinfo.url=location.href+'&type=2';
                Controller.tableinfo.toolbar='#toolbar2';
                Controller.tableinfo.columns[0][Controller.tableinfo.columns[0].length-1].table=table;
                // 初始化表格
                table.bootstrapTable(Controller.tableinfo);

                // 为表格绑定事件
                Table.api.bindevent(table);
            },
        },
        add    : function () {
            Controller.api.bindevent();
        },
        edit    : function () {
            Controller.api.bindevent();
        },
        export   : function () {
            Controller.api.bindevent();
        },
        convert    : function () {
            Controller.api.bindevent();
            $('#contract').trigger('change');
        },
        revoke    : function () {
            Form.api.bindevent($("form[role=form]"), function(data, ret){
                //这里是表单提交处理成功后的回调函数，接收来自php的返回数据
                Fast.api.close(data);//这里是重点
                parent.location.reload();
            });
        },
        tabledetail    : {
            basic: function () {

            },
            product: function () {
                //操作日志
                var table2 = $("#operation_product");
                // 初始化表格
                table2.bootstrapTable({
                    url          : 'qingdongwms/customer/delivery/get_delivery_product?delivery_id='+Config.idinfo.id,
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar: "#toolbar_product",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    columns      : [
                        [
                            {
                                field : 'name', title : '产品名称', operate : 'like', fixedColumns : true, formatter : function (value, row, index) {
                                    return "<a href='javascript:void(0);' class='btn-dialog' " +
                                        "data-url='qingdongwms/product/product/detail/ids/"+row.product_id+"' data-shade='0.3' data-title='产品详情' >" + value + "</a>";
                                }
                            },
                            {field: 'goods.name', title: __('商品')},
                            {field: 'type', title: __('规格')},
                            {field: 'unit', title: __('单位')},
                            {field: 'number', title: __('数量')},
                            {field: 'price', title: __('销售单价（元）')},
                            {field: 'total_price', title: __('销售价格小计（元）'), formatter : function (value, row, index) {

                                    return row.price * row.number;
                            }},
                            {field: 'freight', title: __('运费')},
                        ]
                    ]
                });
                Table.api.bindevent(table2);
            },
            settings4: function () {

                //操作日志
                var table2 = $("#operation_log");
                // 初始化表格
                table2.bootstrapTable({
                    url          : 'qingdongwms/customer/log/index?delivery_id='+Config.idinfo.id,
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar: "#toolbar_log",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    columns      : [
                        [
                            {field: 'staff.name', title: __('员工')},
                            {field: 'content', title: __('内容'),cellStyle:function (value,row,index,field) {
                                    return {
                                        css: {
                                            "min-width": "150px",
                                            "white-space": "nowrap",
                                            "text-overflow": "ellipsis",
                                            "overflow": "hidden",
                                            "max-width":"300px",
                                            'cursor':"pointer"
                                        }
                                    };
                                },formatter:function (value,row,index,field) {
                                    var span=document.createElement('span');
                                    span.setAttribute('title',value);
                                    span.innerHTML = value;
                                    return span.outerHTML;
                                }
                            },
                            {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},

                        ]
                    ]
                });
                Table.api.bindevent(table2);
            },

        },
        detail : function () {
            // 初始化表格参数配置
            Table.api.init({});
            $('.stafflist').popover({
                placement : 'bottom',
                trigger : 'hover'
            });
            //绑定事件
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var panel = $($(this).attr("href"));
                if (panel.length > 0) {
                    Controller.tabledetail[panel.attr("id")].call(this);
                    $(this).on('click', function (e) {
                        $($(this).attr("href")).find(".btn-refresh").trigger("click");
                    });
                }
                //移除绑定的事件
                $(this).unbind('shown.bs.tab');
            });

            //必须默认触发shown.bs.tab事件
            $('ul.nav-tabs li.active a[data-toggle="tab"]').trigger("shown.bs.tab");

            //编辑
            $(document).on('click','#edits',function () {
                var id=$('#deliveryId').val();
                Fast.api.open("qingdongwms/customer/delivery/edit?ids="+id, "发货单编辑",{
                    shadeClose: false,
                    shade: false,
                    maxmin: false,
                    moveOut: false,
                    scrollbars:false,
                    area:["100%", "100%"],
                    callback:function(value){
                        location.reload();
                    },
                });

            });
            //删除
            $("#dels").on('click',function(){
                var id=$('#deliveryId').val();
                Layer.confirm('确定删除发货单吗？', {
                    btn: ['确定','取消']
                },function(index, layero){
                    Fast.api.ajax("qingdongwms/customer/delivery/del?ids="+id,function(data,ret){
                        if(ret.code == 1){
                            Layer.close(index);
                            parent.location.reload();
                        }
                    },function(data,ret){
                    });

                });
            });

            Controller.api.bindevent();
        },
        api    : {
            bindevent : function () {
                $(document).on("fa.event.appendfieldlist", '.fieldlist', function(){
                    //通用的表单组件事件绑定和组件渲染
                    Form.events.selectpage($("form"));
                    Form.events.datetimepicker($("form"));
                }).on('change','.contract_id',function (){
                    var contract_id= $('.contract_id').val();
                    $.post('qingdongwms/customer/delivery/get_contract_product',{contract_id:contract_id},function (data){
                        if(data.code == 1){
                            var result=[];
                            $.each(data.data,function (index,params){
                                var r={};
                                r.contract_product_id=params.id;
                                r.product_id=params.product_id;
                                r.price=params.price;
                                r.number=params.number;
                                if(params.goods){
                                    r.goods=params.goods.name;
                                }
                                r.type=params.type;
                                r.freight=params.freight;
                                result.push(r);
                            });
                            var res=JSON.stringify(result);

                            $('textarea[name="row[product]"]').val(res);
                            $(".fieldlist").trigger("fa.event.refreshfieldlist");
                            $('textarea[name="row[product]"]').trigger("fa.event.refreshfieldlist");
                        }
                    },'json');
                }).on("click", ".select-customer", function(){
                    var $this=$(this);
                    top.Fast.api.open($(this).data("url") , __('Select'), {callback: function (data) {
                            $this.html(data.name);
                            $('[name="'+$this.data('name')+'"]').val(data.id);
                        },area:["100%", "100%"]});
                }).on("click", ".select-contract", function(){
                    var $this=$(this),customer_id=$('[name="row[customer_id]"]').val();
                    if(!customer_id){
                        Layer.msg('请先选择客户');
                        return false;
                    }
                    top.Fast.api.open($(this).data("url")+"&customer_id="+customer_id , __('Select'), {callback: function (data) {
                            $this.html(data.name);
                            $('[name="'+$this.data('name')+'"]').val(data.id);
                            var contract_id = data.id;
                            if(contract_id){
                                $.post('qingdongwms/customer/delivery/get_contract_product',{contract_id:contract_id},function (data){
                                    if(data.code == 1){
                                        var result=[];
                                        $.each(data.data,function (index,params){
                                            var r={};
                                            r.contract_product_id=params.id;
                                            r.product_id=params.product_id;
                                            r.price=params.price;
                                            r.number=params.number;
                                            if(params.goods){
                                                r.goods=params.goods.name;
                                            }
                                            r.type=params.type;
                                            r.freight=params.freight;
                                            result.push(r);
                                        });
                                        var res=JSON.stringify(result);

                                        $('textarea[name="row[product]"]').val(res);
                                        $(".fieldlist").trigger("fa.event.refreshfieldlist");
                                        $('textarea[name="row[product]"]').trigger("fa.event.refreshfieldlist");
                                    }
                                },'json');

                            }
                        },area:["100%", "100%"]});
                });
                $(".selectpage").data("params", function (obj) {
                    var customer_id=$('#customer').val();
                    //obj为SelectPage对象
                    return {ids: customer_id};
                });

                function set_money(){
                    var $price = $('.price');
                    var $number = $('.number');
                    var price=0;
                    $.each($price, function (index, item) {
                        var p = $(item).val(), n = $number.eq(index).val();
                        p = parseFloat(p);
                        n = parseInt(n);
                        price += p * n;
                    });
                    $('#c-money').val(price);
                }
                $(document).on("change", ".product", function(){
                    var $this=$(this);
                    var id=$this.next('input').val();
                    Fast.api.ajax("qingdongwms/customer/delivery/get_product_price?id="+id,function(data,ret){
                        $this.parent().parent().next('td').find('input').val(data.price);
                        $this.parent().parent().parent().find('.goods').html(data.goods.name);
                        $this.parent().parent().parent().find('.type').html(data.type);
                        set_money();
                        return false;
                    });

                }).on("change", ".price", function(){
                    set_money();
                }).on("change", "[name='row[online]']", function(){
                    var online=$(this).val();
                    if(online =='线上'){
                        $('#shop_id').show();
                    }else{
                        $('#shop_id').hide();

                    }
                }).on("change", ".number", function(){
                    set_money();
                }).on("change", "#ratio_id", function(){
                    var ratio=$('#ratio_id').find('option:selected').data('ratio');
                    if(!ratio){
                        $('.table_ratio').hide();
                        return false;
                    }
                    var html="";
                    $.each(ratio,function (index,item){
                       html+="<tr>" +
                           "<td>"+item.ratio+"%<input type='hidden' name='row[ratios]["+index+"][ratio]' value='"+item.ratio+"'></td>" +
                           "<td><input data-source=\"qingdongwms/customer/customer/getteam\"" +
                           "class=\"form-control selectpage\" name=\"row[ratios]["+index+"][staff_id]\" placeholder=\"请选择团队成员\" type=\"text\" value=\"\"></td>" +
                           "</tr>";
                    });
                    $('.table_ratio').find('tbody').html(html);
                    $('.table_ratio').show();
                    Form.events.selectpage($("form"));

                    $(".selectpage").data("params", function (obj) {
                        var customer_id=$('#customer').val()
                        if(!customer_id){
                            layer.msg('请先选择客户');
                            return false;
                        }
                        //obj为SelectPage对象
                        return {ids: customer_id};
                    });
                })
                $(document).on('change','#customer',function (){
                    var url='qingdongwms/customer/delivery/get_contacts_list';
                    url = Fast.api.fixurl(url);
                    var customer_id=$('#customer').val();
                    if(!customer_id){
                        return false;
                    }
                    $.post(url,{'customer_id':customer_id},function (data){
                        var contacts_id=$('#contacts').data('id');

                        if(data.code == 1){
                            var html='<option value="">请选择客户联系人</option>';
                            $.each(data.data,function (index,row){
                                if(contacts_id == row.id){
                                    html+='<option value="'+row.id+'" selected="selected" >'+row.name+'</option>';
                                }else{
                                    html+='<option value="'+row.id+'">'+row.name+'</option>';
                                }
                            })
                            $('#contacts').html(html)
                        }else{
                            layer.alert(data.msg);
                        }
                    },'json');

                    var detail_url='qingdongwms/customer/contract/get_customer_detail';
                    url = Fast.api.fixurl(url);
                    $.post(detail_url,{'customer_id':customer_id},function (data){
                        if(data.code == 1){
                            $('#c-other_45408').val(data.data.address_detail)
                            $('#c-other_63191').val(data.data.other_96880)
                        }else{
                            layer.alert(data.msg);
                        }
                    },'json');
                });
                $('#customer').trigger('change')
                $("[name='row[online]']").trigger('change')
                require(['backend/qingdongwms/common/common'])
                Form.api.bindevent($("form[role=form]"), function(data, ret){
                    //这里是表单提交处理成功后的回调函数，接收来自php的返回数据
                    Fast.api.close(data);//这里是重点
                });
            }
        }
    };
    return Controller;
});